import 'dart:isolate';

import 'package:async/async.dart';
import 'package:snooperlang/snooperlang.dart';

import 'dart:io';

import 'package:lpg2/lpg2.dart';
import 'package:snooperlang/src/AstDumper.dart';
import 'package:snooperlang/src/SnooperLexer.dart';


import 'package:snooperlang/src/snooperParser.dart';
import 'package:snooperlang/src/snooperParsersym.dart';
 isNumber(String str) {
  int length = str.length;
  for (int i = 0; i < length; i += 1) {
    switch(str[i]){
      case 'a':
      case 'A':
      case 'b':
      case 'B':
      case 'c':
      case 'C':
      case 'd':
      case 'D':
      case 'e':
      case 'E':
      case 'f':
      case 'F':
      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
        break;
      default:
        return false;
    }
  }
  return true;

}
// 当A0000003330101时候会被词法分析当成identifier

bool process(String filename){

  var inputChars = File(filename).readAsStringSync(encoding: systemEncoding);
  //inputChars='8';
  inputChars += "\n";
  var lexer = snooperLexer(filename, 4, inputChars); // Create the lexer

  var parser = snooperParser(lexer.getILexStream()); // Create the parser
  //lexer.printTokens = true;
  lexer.lexer(parser.getIPrsStream());
  var tokens = parser.prsStream.tokens;
  for (var i = 0; i < tokens.size()-1; ++i)
  {
    Token token = tokens.get(i);
    var s = token.toString();
    var kind = token.getKind();
    if(kind == snooperParsersym.TK_IDENTIFIER){

      if(!isNumber(s)) {
        continue;
      }
      Token tokenNext = tokens.get(i+1);
      kind = tokenNext.getKind();
      if( kind == snooperParsersym.TK_LPAREN || kind == snooperParsersym.TK_EQUAL) {
         continue;
      }
      token.setKind(snooperParsersym.TK_NUMBER);
    }
  }

  var ast = parser.parser();
  if(ast != null){
    //ASTNode node = ast as ASTNode;
    //AstDumper  dumper= AstDumper() ;
    //node.acceptWithArg(dumper,"");
  }
  return  ast != null;
}

void  testFiles(String path){

  try{
    var  directory  =   Directory(path);
    List<FileSystemEntity> files = directory.listSync();
    for(var f in files){
      print(f.path);

      if(FileSystemEntity.isFileSync(f.path)){
        var filename = f.path;
        process(filename);
      }
    }
  }catch(e){
    print("异常！" + e.toString());
  }
}

void isolateTest() async {
  /// 创建Isolate

  /// 创建一个ReceivePort
  /// Isolate所需参数，必须要有SendPort，SendPort需要ReceivePort创建
  ReceivePort receivePort = ReceivePort();

  /// 第一个参数entryPoint：必须是一个顶层方法或静态方法
  /// 第二个参数message：通常初始化message包含一个sendPort
  Isolate iso = await Isolate.spawn(isoFromSnooperAnalyzer, receivePort.sendPort);
  //创建监听，监听那边发过来的数据和SendPort
  SendPort? sendPort;
  receivePort.listen((message) {
    print("data is $message");
    if(sendPort == null){
      sendPort = message as SendPort;
      //sendPort?.send('message from flutter');
    }
    else{
      if(message is String){
        if(message == '结束'){
          receivePort.close();
          iso.kill();
        }
      }
    }
  });
}

void isoFromSnooperAnalyzer(SendPort sendPort) async {


  final receivePort = ReceivePort();
  sendPort.send(receivePort.sendPort);

  // ---->  将2边sendPort进行绑定
  var path= r'/Users/kuafu/workspace/snooper-project/DCEPApplet/script/trade_fun.txt';
    // path= r"/Users/kuafu/workspace/snooper-project/DCEPApplet/script/0000_upload_cap.txt";
     path=r'/Users/kuafu/workspace/snooper-project/DCEPApplet/script/Per_fun.txt';
    // path = r'/Users/kuafu/workspace/snooper-project/DCEPApplet/script/0006_ep_withdraw.txt';
     //path = r'/Users/kuafu/workspace/snooper-project/DCEPApplet/script/0004_ep_consume.txt';
  if(process(path)){
    sendPort.send('解析成功 isoFromSnooperAnalyzer');
  }
  else{
    sendPort.send('解析失败 isoFromSnooperAnalyzer');
  }
  sendPort.send('结束');

}


void main(List<String> arguments) {
  testFiles(r"/Users/kuafu/workspace/snooper-project/DCEPApplet/script");
 //isolateTest();

}
